import React, { useCallback, useMemo } from "react";
import useWishlistStore from "@/business.InterfaceLayer/hooks/store/localstorage/useWishlistStore";
import WishlistIcon from "../../../shared/icons/favorite.svg?react";
import WishlistIconFilled from "../../../shared/icons/favoriteRed.svg?react";
import { WishlistButtonProps } from "./type";
import ImageAtom from "../../Atoms/Image.Atom";
import ImageEnum from "../../Atoms/Image.Atom/enum";

const WishlistButton: React.FC<WishlistButtonProps> = (props) => {
  const { title, brand, price, img_paths, colors, id } = props;

  const { items, addToWishlist, removeFromWishlist } = useWishlistStore();
  const isInWishlist = useMemo(
    () => items.some((item) => item.id === id),
    [items, id]
  );

  const handleWishlistClick = useCallback(() => {
    if (isInWishlist) {
      removeFromWishlist(id);
    } else {
      addToWishlist({ id, title, brand, price, img_paths, colors, size: "S" });
    }
  }, [
    id,
    isInWishlist,
    addToWishlist,
    removeFromWishlist,
    title,
    brand,
    price,
    img_paths,
    colors,
  ]);

  return (
    <ImageAtom
      onClick={(e) => {
        e.stopPropagation();
        e.preventDefault();
        handleWishlistClick();
      }}
      type={ImageEnum.enum_defaultSvg}
      icon={isInWishlist ? <WishlistIconFilled /> : <WishlistIcon />}
      className="h-6 w-7 fill-tiffany"
    />
  );
};

export default React.memo(WishlistButton);
